package cn.kent;

import cn.kent.util.Employee;
import cn.kent.util.EmployeeData;
import org.junit.Test;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;

/**
 * 测试Stream的中间操作
 * 筛选与切片
 */
public class StreamAPITest1 {
    /**
     * 筛选与切片
     */
    @Test
    public void test() {
        final List<Employee> employees = EmployeeData.getEmployees();
        final Stream<Employee> stream = employees.stream();

        // 查询工资大于1500的员工
        stream.filter(e -> e.getSalary() > 1500).forEach(System.out::println);
//        stream.limit(1).forEach(System.out::println); // stream流每次只能使用一次，再次使用会报错 java.lang.IllegalStateException: stream has already been operated upon or closed

        System.out.println();
        // limit 截断流
        employees.stream().limit(1).forEach(System.out::println);

        System.out.println();
        // skip 跳过前n个元素
        employees.stream().skip(3).forEach(System.out::println);

        System.out.println();
        // distinct() 筛选 - 需要重写hashCode方法和equals方法
        employees.add(new Employee(1010, "刘强东", 10000));
        employees.add(new Employee(1010, "刘强东", 10000));
        employees.add(new Employee(1010, "刘强东", 10000));
        employees.add(new Employee(1010, "刘强东", 10000));
        employees.add(new Employee(1010, "刘强东", 10000));
        employees.add(new Employee(1010, "刘强东", 10000));
        employees.stream().distinct().forEach(System.out::println); // 依赖equals方法和hasCode方法

    }

    //映射
    @Test
    public void test2() {
        final List<String> list = Arrays.asList("aa", "cc", "bb", "dd");
        list.stream().map(str -> str.toUpperCase()).forEach(System.out::println);


        // 获取员工姓名长度大于2的员工姓名
        final List<Employee> employees = EmployeeData.getEmployees();
        final Stream<String> namesStream = employees.stream().map(Employee::getName);
        namesStream.filter(name -> name.length() > 2).forEach(System.out::println);
    }

    /**
     * 排序
     */
    @Test
    public void test3() {

        List<Integer> list = Arrays.asList(1, 34, 5, 6, 12, 345, 67, 82, 10);
        final Stream<Integer> stream = list.stream();
        final Stream<Integer> sorted = stream.sorted();
        sorted.forEach(System.out::println);

        final List<Employee> employees = EmployeeData.getEmployees();
        final Stream<Employee> stream1 = employees.stream();
//        stream1.sorted(new Comparator<Employee>() {
//            @Override
//            public int compare(Employee o1, Employee o2) {
//                return Integer.compare(o1.getSalary(), o2.getSalary());
//            }
//        }).forEach(System.out::println);

        stream1.sorted((o1,o2)->{
            return Integer.compare(o1.getSalary(),o2.getSalary());
        }).forEach(System.out::println);

    }

}
